import Vue from "vue";
import VueRouter from "vue-router";

import Lianxi1 from "@/views/Lianxi/Lianxi1";
import yemian from "@/views/yemian/Yemian";
import login from "@/views/login/Login";
import register from "@/views/Register/register";
import homepage from "@/views/HomePage/homepage";
Vue.use(VueRouter);
// 公共路由
export const constantRoutes = [
    {//练习
        path: "/Lianxi1",
        name: 'Lianxi1',
        component: Lianxi1,
    },
    {
        path: "/yemian",
        name: yemian,
        component: yemian,
        //子路由
        children: [
            {
                path: "homepage",    // 相对路径 首页

                component: () => import('@/views/HomePage/homepage')
            },
            {
                path: "user",    // 相对路径 用户

                component: () => import('@/views/User/user')
            },
            {
                path: "role",    // 相对路径 角色

                component: () => import('@/views/Role/role')
            },
            {
                path: "menu",    // 相对路径 菜单

                component: () => import('@/views/Menu/menu')
            },
            {
                path: "dictionaries",    // 相对路径 字典

                component: () => import('@/views/Dictionaries/dictionaries')
            },

        ],
    },
    {//登陆
        path: "/login",
        name: 'login',
        component: login,
    },
    {//登陆
        path: "/register",
        name: 'register',
        component: register,
    },
]
//登陆
const router =  new VueRouter({
    mode: "history", // 后台服务器也要做相关配置 https://v3.router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
    routes: constantRoutes,
});

//路由守卫
router.beforeEach((to, from, next) => {
    console.log(`Navigating from ${from.path} to ${to.path}`); // 调试信息

    if (to.path === '/login') {
        // 如果当前正在访问登录页但用户已经认证，则重定向到首页
        if (sessionStorage.getItem("ture") != null) {//登陆成功来判断是否sessionStorage是否为空
            console.log('跳转 to /yemian/homepage');
            return next('/yemian/homepage'); // 直接重定向到首页
        }
    } else {
        // 处理需要认证的页面，如果用户未认证，则重定向到登录页
        // if (!isAuthenticated && to.path !== '/login') {
        //     console.log('User is not authenticated, redirecting to /login');
        //     console.log('isAuthenticated！！！'+isAuthenticated);
        //     return next('/login'); // 进行重定向
        // }
        if (sessionStorage.getItem("ture") == null) {
            console.log('sessionStorage为空！返回 /login');

            return next('/login'); // 进行重定向
        }
    }

    // 允许正常访问
    next();
});

export default router;
